package com.imooc.diners.service;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.boot.web.servlet.filter.ApplicationContextHeaderFilter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.imooc.commons.constant.RedisKeyConstant;
import com.imooc.commons.utils.AssertUtil;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

/**
 * \* @author: bear
 * \* Date: 2021-07-11-18:54
 * \* describe:
 */
@Service
public class SendVerifyCodeService {
	@Resource
	private RedisTemplate<String,String> redisTemplate;

	//发送验证码
	public void send(String phone){
		//验证非空
		AssertUtil.isNotEmpty(phone,"手机号不能为空");
		//根据手机号查询是否已生成验证码，已生成直接返回
		if(!checkCodeIsExpired(phone)){
			return;
		}
		//生成6位数的验证码
		String code = RandomUtil.randomNumbers(6);
		//调用短信服务发送短信
		// 发送成功，讲code存入redis
		String key = RedisKeyConstant.verify_code.getKey()+phone;
		redisTemplate.opsForValue().set(key, code, 60, TimeUnit.SECONDS);
	}
	/**
	 * 根据手机号查询是否已生成验证码
	 *
	 * @param phone
	 * @return
	 */
	private boolean checkCodeIsExpired(String phone) {
		String key = RedisKeyConstant.verify_code.getKey() + phone;
		String code = redisTemplate.opsForValue().get(key);
		return StrUtil.isBlank(code) ? true : false;
	}
	/**
	 * 根据手机号获取验证码
	 *
	 * @param phone
	 * @return
	 */
	public String getCodeByPhone(String phone) {
		String key = RedisKeyConstant.verify_code.getKey() + phone;
		return redisTemplate.opsForValue().get(key);
	}
}
